package com.enbatis.mybatisplugs.service.impl;

import com.enbatis.mybatisplugs.base.BaseServiceImpl;


import com.enbatis.mybatisplugs.base.IRedisService;
import com.enbatis.mybatisplugs.commons.sql.Wrapper;
import com.enbatis.mybatisplugs.commons.utils.IdWorker;
import com.enbatis.mybatisplugs.commons.utils.MD5Util;
import com.enbatis.mybatisplugs.commons.utils.ResultReturn;
import com.enbatis.mybatisplugs.entity.SysDept;
import com.enbatis.mybatisplugs.entity.SysUser;
import com.enbatis.mybatisplugs.entity.SysUserRelDept;
import com.enbatis.mybatisplugs.entity.vo.SysUserRelDeptVO;
import com.enbatis.mybatisplugs.entity.vo.SysUserVO;
import com.enbatis.mybatisplugs.mapper.SysUserMapper;
import com.enbatis.mybatisplugs.plugin.Pages;
import com.enbatis.mybatisplugs.service.MongoDbService;
import com.enbatis.mybatisplugs.service.SysDeptService;
import com.enbatis.mybatisplugs.service.SysUserRelDeptService;
import com.enbatis.mybatisplugs.service.SysUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.stream.Collectors;

/**
* 描述：
* @author wangweidong
* @date 2019-06-15 10:31:25
*/
@Slf4j
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private MongoDbService mongoDbService;
    @Autowired
    private IRedisService redisService;

    @Autowired
    private SysUserRelDeptService sysUserRelDeptService;

    @Autowired
    private SysDeptService sysDeptService;

    @Override
    public boolean insertUser(SysUserVO userVO) {
        SysUser user=new SysUser();
        BeanUtils.copyProperties(userVO,user);

        String psd=user.getPassword();
        String salt= MD5Util.getSalt(psd);
        user.setPassword(MD5Util.generatePsd(psd,salt));
        user.setSalt(salt);

        try {
            this.insert(user);
            List<Long> deptIds=userVO.getDeptIds();
            if (CollectionUtils.isNotEmpty(deptIds)){
                List<SysUserRelDept> saveList=new ArrayList<>();
                for (Long depId:deptIds) {
                    SysUserRelDept relDept=new SysUserRelDept();
                    relDept.setUserId(user.getId());
                    relDept.setDeptId(depId);
                    relDept.setCtime(new Date());
                    relDept.setDeleted(0);
                    saveList.add(relDept);

                }
                if (CollectionUtils.isNotEmpty(saveList)){
                    sysUserRelDeptService.saveBatch(saveList);
                }
            }
        }catch (Exception e){
            String message= e.getMessage();
            if (message.contains("unique_username")){
                return false;
            }else{
                log.error("保存失败"+e.getMessage(),e);
                return false;
            }
        }

        return true;
    }

    @Override
    public void uploadHeadPhoto(String businessId, MultipartFile file){
        if(StringUtils.isBlank(businessId)){
          return;
        }
        Long id =Long.parseLong(businessId);
        String key= mongoDbService.saveFile(file);
        if (StringUtils.isBlank(key)){
            log.error("头像上传失败");
            return;
        }
        SysUser sysUser=new SysUser();
        sysUser.setId(id);
        sysUser.setUri(key);
        updateById(sysUser);
        redisService.set("headPhoto:"+id,"http://localhost:9888/v1/oss/preview?file_id="+key);
    }

    @Override
    public String previewHeadPhoto(Long id) {
        if (redisService.get("headPhoto:"+id)==null){
            SysUser sysUser=getById(id);
            if (null==sysUser){
                return null;
            }
            if (StringUtils.isBlank(sysUser.getUri())){
                return null;
            }
            redisService.set("headPhoto:"+id,"http://localhost:9888/v1/oss/preview?file_id="+sysUser.getUri());
            return "http://localhost:9888/v1/oss/preview?file_id="+sysUser.getUri();

        }else{
            return redisService.get("headPhoto:"+id).toString();
        }



    }

    @Override
    public Pages<SysUserVO> pageVO(Page<SysUserVO> page, SysUserVO userVO) {
        Page returnPage= PageHelper.startPage(page.getPageNum(),page.getPageSize(),page.getOrderBy());
        List<SysUserVO> list= baseMapper.selectVOList(userVO);
        if (CollectionUtils.isEmpty(list)){
            return new Pages<>(returnPage);
        }
        List<Long> userIds=list.stream().map(u->{
            return u.getId();
        }).collect(Collectors.toList());
        List<SysUserRelDeptVO>  listRel= sysUserRelDeptService.listVOByUsers(userIds);
        if (CollectionUtils.isEmpty(listRel)){
             return new Pages<>(returnPage);
        }

        for (SysUserVO sysUserVO:list) {
            StringBuffer depts=new StringBuffer();
            for (SysUserRelDeptVO relDeptVO:listRel) {
                if (relDeptVO.getUserId().equals(sysUserVO.getId())){
                    depts.append(relDeptVO.getDept()).append("、");
                }
            }
            if (depts.length()>0){
                sysUserVO.setDepts(depts.toString().substring(0,depts.length()-1));
            }
        }


        return new Pages<>(returnPage);
    }
}
